<?php
/**
 *
 */
namespace app\home\controller\order;

use app\home\controller\Base;
use app\common\model\Order;
class Handle extends Base
{

	private $params;

	public function __construct(){
		parent::__construct();
		//token验证
		// if(false == Base::checkToken()){
		// 	$this->error('token error!');
		// }
		// 参数去token
		$params = $this->request->param();
		//unset($params['token']);
		$this->params = $params;
	}


    /**
     * [checkGoods 确认收货]
     * @return [type] [description]
     */
    public function checkGoods(){
        $param = $this->params;
        if(isset($param['id']))return json(['code'=>0,'msg'=>'参数错误']);
        $data = model('Order')->getOneRow(['id'=>$param['id']]);
        if($data && $data['status'] == '2'){
            //处理收货
            model('Order')->updateOrder($params['id'],['status'=>2]);
            return json(['code'=>1,'msg'=>'确认收货成功',]);
        }
        return json(['code'=>0,'msg'=>'此订单目前无法执行此操作']);
    }

    /**
     * [payCoin 货币判断]
     * @param  array  $data   [货币类型key 货币额度val]
     * @param  string $credit [积分]
     * @return [type]         [description]
     */
	public static function payCoin($user='',$data=[],$credit=0){
        //检查用户货币是否充足
        if($credit != '0'){
            $res = model('Coin')->tagCoin('c_jifen');
            $credit_res =model('MemberCoin')->isHigh(['uid'=>$user,'coin_id'=>$res['id'],'amount'=>['gt',$credit]]);//判断积分
            if(false !== $credit_res)return ['code'=>0,'data'=>'用户积分不足'];
        }
        foreach ($data as $k => $v) {
           $res =model('MemberCoin')->isHigh(['uid'=>$user,'coin_id'=>$k,'amount'=>['gt',array_sum($v)]]);
           if(false !== $res){
                return $res;
           }
        }
        return false;
	}

	private function changeCoin($data=[],$order_id='',$credit=0){
        if($credit != '0'){
            $res = model('Coin')->tagCoin('c_jifen');
            $msg = '支付订单'.$order_id.'使用'.$credit.$res['coin_name'];
            model('Order')->orderMemberCoinRecord('dec',UID,$res['id'],$credit,$msg);
        }
        foreach ($data as $k => $v){
            $coin_res = model('Coin')->coinData($k);
            $v = array_sum($v);
            $msgs = '支付订单'.$order_id.'使用'.$v.$coin_res['coin_name'];
            model('Order')->orderMemberCoinRecord('dec',UID,$k,$v,$msgs);
        }
        return true;
	}

    /**
     * [getOrder 用户下单]
     * @return [type] [description]
     */
    public function getOrder(){
        $params = $this->params;
        $result = $this->validate($params,'Order.home_add');
        if(true !== $result) {
            $this->error($result);
        }
        unset($params['captcha']);
        $params['des'] = !empty($params['des'])?$params['des']:'';
        if(false == model('Member')->ispayPwd(UID,$params['paypwd']))$this->error('交易密码错误');

        //查看购物车中商品
        $row = cookie('cartlist');
        if(empty($row)){
            $this->error('购物车为空');
            return;
        }
        $total_money = 0;
        $credit = 0;
        $score = 0;
        $res = [];
        $goods_row = '';
        $des = '';
        $order_no = create_guid();
        foreach ($row as $key => $v) {
            $rows = model('MallGoods')->getOneDataById($v['id'],'credit,title,coin_id,score');
            //积分抵消
            if($rows['credit']){
                 $res['credit'] = intval($rows['credit'])*intval($v['number']);
                 $credit += intval($rows['credit'])*intval($v['number']);//积分合并
            }else{
                 $res['credit'] = 0;
            }
            if(isset($rows['score'])){
                 $res['score'] = intval($rows['score'])*intval($v['number']);
                 $score += intval($rows['score'])*intval($v['number']);//业绩合并
            }
            //产生业绩
            //end//
            $res['amount'] = intval($v['price'])*intval($v['number'])-intval($res['credit']);//减去积分所需总额
            $isHigh[$rows['coin_id']][] = $res['amount'];
            $total_money += intval($res['amount']);
            $des .= $rows['title'].'*'.$v['number'].'单价:'.$v['price'].'共计:'.$res['amount'].'/'.$rows['coin_name'].',积分抵扣'.$res['credit'].' ';
            $goods_row .= $v['id'].','.$v['number'].'#';
            //先添加订单详情,避免重复一步
            $data = ['order_id'=>$order_no,'gid'=>$v['id'],'number'=>$v['number'],'uid'=>UID,'amount'=>$res['amount'],'coin_id'=>$rows['coin_id'],'create_time'=>time(),'score'=>$res['score'],'credit'=>$res['credit']];
            model('OrderDetails')->add($data);
        }
        //商品库存判断
        $goodsTotal = self::goodsTotal($goods_row);
        if(false !== $goodsTotal){
            $this->error('商品库存不足，请重新购买商品');
        }
        //货币判断,返回true 则货币不足
        $res = self::payCoin(UID,$isHigh,$credit);
        if($res){
            model('OrderDetails')->del(['order_id'=>$order_no]);
            $this->error($res['data']);
        }
        //足够则增减货币,添加订单,减少库存
        if(self::changeCoin($isHigh,$order_no,$credit)){
            $params['msg'] = '中午或者下午送';
            $data = [
                'order_id' => $order_no,
                'uid' => UID,
                'amount' => $total_money,
                'des'=>serialize($des),
                'address_id'=>$params['aid'],
                'status' => 1,
                'score'=>$score,
                'credit'=>$credit,
                'create_time' => time(),
                'msg'=>$params['msg'],
            ];
            model('Order')->addOrder($data);
            self::decTotal('dec',$goods_row);//减少库存
            cookie('cartlist',null);//清空购物车
            $this->success('支付成功',url('order.show/index'));
        }
        $this->error('支付失败');
    }

    /**
     * [decTotal 减少商品库存]
     * @param  string $type [description]
     * @param  string $row  [description]
     * @return [type]       [description]
     */
    private function decTotal($type='',$row=''){
        $row = self::strMark($row);
        foreach ($row as $key => $value){
            if(isset($key))unset($row[$key]);
            $rows = explode(',',$value);

            model('MallGoods')->decTotal(['id'=>$rows[0]],$rows[1]);
            //增加销量
            model('MallGoods')->incNum(['id'=>$rows[0]],'sales_num',$rows[1]);
        }
        return true;
    }

    /**
     * [goodsTotal 商品库存判断]
     * @param  string $row  [description]
     * @return [type]       [description]
     */
    private function goodsTotal($data=''){
        $row = self::strMark($data);
        foreach ($row as $key => $value){
            $rows = explode(',',$value);
            $res = model('MallGoods')->goodsTotal(['id'=>$rows[0],'total'=>['egt',$rows[1]]]);
        }
        return $res;
    }

    /**
     * [strMark 字符串处理]
     * @param  string $row [description]
     * @return [type]      [description]
     */
    private function strMark($row=''){
        $newstr = substr($row,0,strlen($row)-1);
        $row = explode('#',$newstr);
        return $row;
    }
}